package com.aube.activity;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.text.style.ImageSpan;
import android.view.View;

import com.aube.R;
import com.aube.model.MessageItem;
import com.aube.model.MessageModel;

import java.io.InputStream;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;

import master.flame.danmaku.controller.IDanmakuView;
import master.flame.danmaku.danmaku.loader.ILoader;
import master.flame.danmaku.danmaku.loader.IllegalDataException;
import master.flame.danmaku.danmaku.loader.android.DanmakuLoaderFactory;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDisplayer;
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.model.android.SpannedCacheStuffer;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.danmaku.parser.IDataSource;
import master.flame.danmaku.danmaku.parser.android.BiliDanmukuParser;

/**
 * Created by huyaonan on 15/12/12.
 */
public class DanmukuFlameHelper {

    private IDanmakuView mDanmakuView;
    private BaseDanmakuParser mParser;
    private DanmakuContext mContext;
    private AtomicBoolean mIsPrepared = new AtomicBoolean(false);
    private MessageModel mTemp;

    private BaseDanmakuParser createParser(InputStream stream) {
        if (stream == null) {
            return new BaseDanmakuParser() {

                @Override
                protected Danmakus parse() {
                    return new Danmakus();
                }
            };
        }

        ILoader loader = DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_BILI);

        try {
            loader.load(stream);
        } catch (IllegalDataException e) {
            e.printStackTrace();
        }
        BaseDanmakuParser parser = new BiliDanmukuParser();
        IDataSource<?> dataSource = loader.getDataSource();
        parser.load(dataSource);
        return parser;
    }

    private BaseCacheStuffer.Proxy mCacheStufferAdapter = new BaseCacheStuffer.Proxy() {

        @Override
        public void prepareDrawing(final BaseDanmaku danmaku, boolean fromWorkerThread) {
            //加载远程url图片, 根据你的条件检查是否需要需要更新弹幕
            if (danmaku.text instanceof Spanned) {
                //加载图片, 完了刷新
            }
        }

        @Override
        public void releaseResource(BaseDanmaku danmaku) {
            //清理含有ImageSpan的text中的一些占用内存的资源 例如drawable
        }
    };

    private SpannableStringBuilder createSpannable(Drawable drawable) {
        String text = "bitmap";
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
        ImageSpan span = new ImageSpan(drawable);//ImageSpan.ALIGN_BOTTOM);
        spannableStringBuilder.setSpan(span, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableStringBuilder.append("图文混排");
        spannableStringBuilder.setSpan(new BackgroundColorSpan(Color.parseColor("#8A2233B1")), 0, spannableStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        return spannableStringBuilder;
    }

    public void init(IDanmakuView danmakuView) {
        mDanmakuView = danmakuView;

        // 设置最大显示行数
        HashMap<Integer, Integer> maxLinesPair = new HashMap<Integer, Integer>();
        maxLinesPair.put(BaseDanmaku.TYPE_SCROLL_RL, 5); // 滚动弹幕最大显示3行
        // 设置是否禁止重叠
        HashMap<Integer, Boolean> overlappingEnablePair = new HashMap<Integer, Boolean>();
        overlappingEnablePair.put(BaseDanmaku.TYPE_SCROLL_RL, true);
        overlappingEnablePair.put(BaseDanmaku.TYPE_FIX_TOP, true);

        mContext = DanmakuContext.create();
        mContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN, 3).setDuplicateMergingEnabled(false).setScrollSpeedFactor(1.2f).setScaleTextSize(1.2f)
                .setCacheStuffer(new SpannedCacheStuffer(), mCacheStufferAdapter) // 图文混排使用SpannedCacheStuffer
                .setMaximumLines(maxLinesPair)
                .preventOverlapping(overlappingEnablePair);
    }

    public void startDanmaku(Context context) {
        if (mDanmakuView != null) {
            mDanmakuView.setVisibility(View.VISIBLE);
            mParser = createParser(context.getResources().openRawResource(R.raw.comment_new));
            mDanmakuView.setCallback(new master.flame.danmaku.controller.DrawHandler.Callback() {
                @Override
                public void updateTimer(DanmakuTimer timer) {
                }

                @Override
                public void drawingFinished() {

                }

                @Override
                public void danmakuShown(BaseDanmaku danmaku) {
//                    Log.d("DFM", "danmakuShown(): text=" + danmaku.text);
                }

                @Override
                public void prepared() {
                    mDanmakuView.start();

                    mIsPrepared.set(true);
                    importDanmuMap(mTemp);
                }
            });
            mDanmakuView.prepare(mParser, mContext);
            mDanmakuView.showFPS(false);
            mDanmakuView.enableDanmakuDrawingCache(true);
        }
    }

    public void onPause() {
        if (mDanmakuView != null && mDanmakuView.isPrepared()) {
//            mDanmakuView.clearDanmakusOnScreen();
            mDanmakuView.pause();
        }
    }

    public void onResume() {
        if (mDanmakuView != null && mDanmakuView.isPrepared() && mDanmakuView.isPaused()) {
            mDanmakuView.resume();
        }
    }

    public void onSeek(long target) {
        try {
            if (mDanmakuView != null)
                mDanmakuView.seekTo(target);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onDestroy() {
        if (mDanmakuView != null) {
            mTemp = null;
            if(mParser != null)
                mParser.release();
            // dont forget release!
            mDanmakuView.clearDanmakusOnScreen();
            mDanmakuView.hideAndPauseDrawTask();
            mDanmakuView.release();
            mDanmakuView = null;
            mParser = null;
        }
    }

    /**
     * 设置弹幕的一些属性
     * @param text
     * @param time
     * @param fromU
     */
    public void addDanmaku(String text, long time, boolean fromU) {
        try {
            BaseDanmaku danmaku = mContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
            if (danmaku == null || mDanmakuView == null) {
                return;
            }
            danmaku.text = text;
            danmaku.padding = 5;
            danmaku.priority = 1;  // 一定会显示, 一般用于本机发送的弹幕
            danmaku.isLive = true;
            danmaku.textColor = Color.WHITE;

            danmaku.time = time;
            danmaku.textSize = 15f * (mParser.getDisplayer().getDensity() - 0.6f);
            if(fromU) {
                danmaku.borderColor = Color.WHITE;
                danmaku.padding = 10;
                danmaku.radius = 5;
            }

            mDanmakuView.addDanmaku(danmaku);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addDanmaku(String text) {
        if(mDanmakuView == null)
            return;
        addDanmaku(text, mDanmakuView.getCurrentTime(), true);
    }

    public void importDanmu(MessageItem item) {
        if(item == null)
            return;
        addDanmaku(item.content, item.videoTime, false);
    }

    public void importDanmuMap(final MessageModel model) {
        if(model == null)
            return;
        if(!mIsPrepared.get()) {
            mTemp = model;
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(model.data == null)
                    return;

                for(MessageItem item : model.data)
                    importDanmu(item);
            }
        }).start();
    }

    public void hide() {
        mDanmakuView.hide();
    }

    public void show() {
        mDanmakuView.show();
    }

    public boolean isOn() {
        return mDanmakuView.isShown();
    }

}
